package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.*;
import cc.rengu.igas.momp.common.dao.impl.*;
import cc.rengu.igas.momp.common.entity.*;
import cc.rengu.igas.momp.common.enums.*;
import cc.rengu.igas.momp.common.util.CommonMessageCheck;
import cc.rengu.igas.momp.facade.bean.*;
import cc.rengu.igas.momp.facade.request.MchntQueryMcDetailInfoRequest;
import cc.rengu.igas.momp.facade.response.MchntQueryMcDetailInfoResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户查询营销活动详情接口实现
 *
 * @author liujinan
 * @version 1.0.0
 * @date 2020/06/19
 */

public class MchntQueryMcDetailInfoService extends RadpService {

    private String globalInstId;
    private String globalQueryType;
    private String globalQueryRole;
    private String globalQueryId;
    private String globalMcNo;
    private String globalTxnDate;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
            MchntQueryMcDetailInfoRequest mchntQueryMcDetailInfoRequest = new MchntQueryMcDetailInfoRequest();
            ConvertUtil.convertOutput(mchntQueryMcDetailInfoRequest);

            MchntQueryMcDetailInfoResponse mchntQueryMcDetailInfoResponse = new MchntQueryMcDetailInfoResponse();
            mchntQueryMcDetailInfoResponse.setHeader(mchntQueryMcDetailInfoRequest.getHeader());
            BizResponse<MchntQueryMcDetailInfoResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(mchntQueryMcDetailInfoResponse);

            String timeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
            globalQueryType = mchntQueryMcDetailInfoRequest.getQueryType();
            globalQueryId = mchntQueryMcDetailInfoRequest.getQueryId();
            globalQueryRole = mchntQueryMcDetailInfoRequest.getQueryRole();
            globalInstId = mchntQueryMcDetailInfoRequest.getHeader().getInstId();
            globalMcNo = mchntQueryMcDetailInfoRequest.getMcNo();
            globalTxnDate = mchntQueryMcDetailInfoRequest.getHeader().getTransDate();

            rglog.info("机构<{}>在<{}>由<{}>开始查询减免类营销活动详细信息流程", globalInstId, timeStamp, globalQueryId);

            //报文检查
            CommonMessageCheck.checkBizMessageHeader(globalQueryType, globalQueryId, globalQueryRole, rglog);

            /* 检查营销活动编号 */
            if (StringUtil.isNullorEmpty(globalMcNo)) {
                rglog.error("法人机构号<{}>的操作员<{}>的营销活动编号为空!", globalInstId, globalQueryId);
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            // 服务调用
            BizResponse<MchntQueryMcDetailInfoResponse> bizResponseNew = mchntQueryMcDetailInfo(xmlTreeUtil, mchntQueryMcDetailInfoRequest, mchntQueryMcDetailInfoResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * 查询营销活动详细信息
     *
     * @param xmlTreeUtil                    内部XML树
     * @param mchntQueryMcDetailInfoRequest  活动详情查询接口请求报文
     * @param mchntQueryMcDetailInfoResponse 活动详情查询接口应答报文
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.MchntQueryMcDetailInfoResponse> 类活动详情查询接口应答报文
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/19 14:50
     */
    private BizResponse<MchntQueryMcDetailInfoResponse> mchntQueryMcDetailInfo(XmlTreeUtil xmlTreeUtil, MchntQueryMcDetailInfoRequest mchntQueryMcDetailInfoRequest, MchntQueryMcDetailInfoResponse mchntQueryMcDetailInfoResponse) throws Exception {

        BizResponse<MchntQueryMcDetailInfoResponse> bizResponse = new BizResponse<>();

        //营销活动类型
        String mcType = globalMcNo.substring(2, 4);

        //判断查询的类型,只有商户才能查询
        if (QueryTypeEnum.MCHNT_QYERY_TYPE.getQueryTypeCode().equals(globalQueryType)) {
            //根据商户编号查询商圈编号
            String mchntNo = globalQueryId;
            String mchntArea = null;
            //查询商户基本信息表
            TBMchntBaseInfo tbMchntBaseInfo = selectMompMchntBaseInfoByPrimaryKey(globalInstId, mchntNo);
            if (null == tbMchntBaseInfo) {
                rglog.error("查询法人机构<{}>商户<{}>基本信息失败!", globalInstId, mchntNo);
                throw new BizException(RespCodeEnum.NO_TRANS_RECORD.getRespCode(), RespCodeEnum.NO_TRANS_RECORD.getRespDesc());
            } else {
                //商圈编号
                mchntArea = tbMchntBaseInfo.getMchntArea();
            }
            //商户查询营销活动详细信息
            if (McTypeEnum.REDUCTION_FIXED_AMOUNT.getMcTypeCode().equals(mcType) ||
                    McTypeEnum.REDUCTION_RANDOM_AMOUNT.getMcTypeCode().equals(mcType) ||
                    McTypeEnum.REDUCTION_FIXED_RATE.getMcTypeCode().equals(mcType) ||
                    McTypeEnum.REDUCTION_RANDOM_RATE.getMcTypeCode().equals(mcType)) {
                //判断查询类型
                MoMcListInfoInObj moMcListInfoInObj = new MoMcListInfoInObj();
                //机构编码
                moMcListInfoInObj.setInstId(globalInstId);
                //营销活动编号
                moMcListInfoInObj.setMcNo(globalMcNo);
                //营销活动类型
                moMcListInfoInObj.setMcType(mcType);
                //商户编号
                moMcListInfoInObj.setMchntNo(mchntNo);
                //商圈编号
                moMcListInfoInObj.setMchntArea(mchntArea);

                rglog.info("减免类营销活动<{}>信息查询开始...", globalMcNo);
                queryMoneyOffMcDetailInfoByMchnt(mchntQueryMcDetailInfoResponse, moMcListInfoInObj, mchntNo);

            } else if (McTypeEnum.COUPON_ALL.getMcTypeCode().equals(mcType) ||
                    McTypeEnum.COUPON_FREE.getMcTypeCode().equals(mcType) ||
                    McTypeEnum.COUPON_PAID.getMcTypeCode().equals(mcType)) {
                //判断查询类型
                CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
                //机构编码
                cpMcListInfoInObj.setInstId(globalInstId);
                //营销活动编号
                cpMcListInfoInObj.setMcNo(globalMcNo);
                //营销活动类型
                cpMcListInfoInObj.setMcType(mcType);
                //商户编号
                cpMcListInfoInObj.setMchntNo(mchntNo);
                //商圈编号
                cpMcListInfoInObj.setMchntArea(mchntArea);
                rglog.info("卡券类营销活动<{}>信息查询开始...", globalMcNo);
                queryCouponMcDetailInfoByMchnt(mchntQueryMcDetailInfoResponse, cpMcListInfoInObj, mchntNo);

            } else {
                rglog.error("机构<{}>的营销活动<{}>的活动类型为<{}>,不支持的活动类型", globalInstId, globalMcNo, mcType);
                throw new BizException(RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespCode(), RespCodeEnum.NOT_SUPPORTED_MC_TYPE_ERROR.getRespDesc());
            }

        } else {
            //其他查询角色不支持
            rglog.error("当前<{}>角色的查询用户<{}>无权限操作数据!", globalQueryRole, globalQueryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespDesc());

        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        mchntQueryMcDetailInfoResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        mchntQueryMcDetailInfoResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntQueryMcDetailInfoResponse);

        return bizResponse;
    }

    /**
     * 商户查询减免类营销活动详细信息
     *
     * @param mchntQueryMcDetailInfoResponse 活动详情查询接口应答报文
     * @param moMcListInfoInObj              营销活动列表查询使用实体类入参
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/19
     */
    private void queryMoneyOffMcDetailInfoByMchnt(MchntQueryMcDetailInfoResponse mchntQueryMcDetailInfoResponse,
                                                  MoMcListInfoInObj moMcListInfoInObj, String mchntNo) throws Exception {

        //查询营销活动基本信息
        TMMcMoneyOffInfo tmMcMoneyOffInfo;
        if (StringUtil.isNullorEmpty(moMcListInfoInObj.getMchntArea())) {
            tmMcMoneyOffInfo = selectMoneyOffMcDetailInfoByMchnt(moMcListInfoInObj);
        } else {
            tmMcMoneyOffInfo = selectMoneyOffMcDetailInfoByMchntWithArea(moMcListInfoInObj);
        }
        if (null == tmMcMoneyOffInfo) {
            rglog.error("机构<{}>的减免类营销活动<{}>的基本信息查询失败!商户无权限查看数据或不存在该营销活动", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MONEY_OFF_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_MONEY_OFF_MC_DETAIL_ERROR.getRespDesc());
        }
        //查询营销活动规则信息
        List<TMMcMoneyOffRuleInfo> mcMoneyOffRuleInfoList = getMoneyOffMcRuleListInfo();
        if (null == mcMoneyOffRuleInfoList || mcMoneyOffRuleInfoList.isEmpty()) {
            rglog.error("机构<{}>的减免类营销活动<{}>的减免类规则查询失败!", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespDesc());
        }

        /* 查询营销活动用户信息 */
        List<TMMcUserInfo> mcUserInfoList = getAllMcUserListInfo();
        if (null != mcUserInfoList && !mcUserInfoList.isEmpty()) {
            List<McUserInfoBean> mcUserInfoBeanList = mcUserInfoList.stream().map(this::convertMcUserInfo).collect(Collectors.toList());
            //活动用户信息
            mchntQueryMcDetailInfoResponse.setUserInfoList(mcUserInfoBeanList);
        }

        //生成接口响应所需的营销活动数据
        ToClientMcInfoBean moneyOffToClientMcInfoBean = moneyOffConvertMcInfo(tmMcMoneyOffInfo);
        mchntQueryMcDetailInfoResponse.setMcInfo(moneyOffToClientMcInfoBean);
        //规则信息
        List<MchntQueryMcRuleInfoBean> mcMoneyOffRuleInfoBean = moneyOffConvertMcRuleInfo(tmMcMoneyOffInfo, mcMoneyOffRuleInfoList);
        mchntQueryMcDetailInfoResponse.setRuleInfoList(mcMoneyOffRuleInfoBean);

        //减免活动统计数据
        MoneyOffMcStatInfoBean moneyOffMcStatInfoBean = getMoneyOffMcStatInfo(tmMcMoneyOffInfo, mchntNo, McTypeEnum.MC_TYPE_MO.getMcTypeCode());
        mchntQueryMcDetailInfoResponse.setMoneyOffMcStatInfo(moneyOffMcStatInfoBean);
    }

    /**
     * 商户查询卡券类营销活动详细信息
     *
     * @param mchntQueryMcDetailInfoResponse 活动详情查询接口应答报文
     * @param cpMcListInfoInObj              营销活动列表查询使用实体类入参
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/20
     */
    private void queryCouponMcDetailInfoByMchnt(MchntQueryMcDetailInfoResponse mchntQueryMcDetailInfoResponse,
                                                CpMcListInfoInObj cpMcListInfoInObj, String mchntNo) throws Exception {
        /* 查询营销活动基本信息 */
        TMMcCouponInfo tmMcCouponInfo;
        if (StringUtil.isNullorEmpty(cpMcListInfoInObj.getMchntArea())) {
            tmMcCouponInfo = selectCouponMcDetailInfoByMchnt(cpMcListInfoInObj);
        } else {
            tmMcCouponInfo = selectCouponMcDetailInfoByMchntWithArea(cpMcListInfoInObj);
        }
        if (null == tmMcCouponInfo) {
            rglog.error("机构<{}>的卡券类营销活动<{}>的基本信息查询失败!商户无权限查看数据或不存在该营销活动", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MONEY_OFF_MC_DETAIL_ERROR.getRespCode(), RespCodeEnum.GET_MONEY_OFF_MC_DETAIL_ERROR.getRespDesc());
        }

        //查询营销活动规则信息
        List<TMMcCouponRuleInfo> mcCouponRuleInfoList = getCouponMcRuleListInfo();
        if (null == mcCouponRuleInfoList || mcCouponRuleInfoList.isEmpty()) {
            rglog.error("机构<{}>的卡券类营销活动<{}>的卡券类规则查询失败!", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespDesc());
        }

        /* 查询营销活动用户信息 */
        List<TMMcUserInfo> mcUserInfoList = getAllMcUserListInfo();
        if (null != mcUserInfoList && !mcUserInfoList.isEmpty()) {
            List<McUserInfoBean> mcUserInfoBeanList = mcUserInfoList.stream().map(this::convertMcUserInfo).collect(Collectors.toList());
            //活动用户信息
            mchntQueryMcDetailInfoResponse.setUserInfoList(mcUserInfoBeanList);
        }

        //生成接口响应所需的营销活动数据
        ToClientMcInfoBean moneyOffToClientMcInfoBean = couponConvertMcInfo(tmMcCouponInfo);
        mchntQueryMcDetailInfoResponse.setMcInfo(moneyOffToClientMcInfoBean);
        //规则信息
        List<MchntQueryMcRuleInfoBean> mcMoneyOffRuleInfoBean = couponConvertMcRuleInfo(mcCouponRuleInfoList);
        mchntQueryMcDetailInfoResponse.setRuleInfoList(mcMoneyOffRuleInfoBean);

        //卡券活动统计数据
        CouponMcStatInfoBean couponMcStatInfoBean = getCouponMcStatInfo(tmMcCouponInfo, mchntNo, McTypeEnum.MC_TYPE_CP.getMcTypeCode());
        mchntQueryMcDetailInfoResponse.setCouponMcStatInfo(couponMcStatInfoBean);
    }

    /**
     * 商户查询营销活动基本信息表数据,无商圈
     *
     * @param moMcListInfoInObj 营销活动列表查询使用实体类入参
     * @return cc.rengu.igas.momp.common.entity.TMMcMoneyOffInfo 减免类营销活动信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/19 19:10
     */
    private TMMcMoneyOffInfo selectMoneyOffMcDetailInfoByMchnt(MoMcListInfoInObj moMcListInfoInObj) throws Exception {
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.selectMoneyOffMcDetailInfoByMchnt(moMcListInfoInObj);
    }

    /**
     * 商户查询营销活动基本信息表数据,有商圈
     *
     * @param moMcListInfoInObj 营销活动列表查询使用实体类入参
     * @return cc.rengu.igas.momp.common.entity.TMMcMoneyOffInfo 减免类营销活动信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/19 19:10
     */
    private TMMcMoneyOffInfo selectMoneyOffMcDetailInfoByMchntWithArea(MoMcListInfoInObj moMcListInfoInObj) throws Exception {
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.selectMoneyOffMcDetailInfoByMchntWithArea(moMcListInfoInObj);
    }


    /**
     * 获取减免类营销活动规则信息列表(正式表)
     *
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMMcMoneyOffRuleInfo> 减免类营销活动规则表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/19 18:40
     */
    private List<TMMcMoneyOffRuleInfo> getMoneyOffMcRuleListInfo() throws Exception {
        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        return mcRuleInfoMapper.selectMoneyOffRuleInfoList(globalInstId, globalMcNo);
    }

    /**
     * 获取卡券类营销活动规则信息列表(正式表)
     *
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMMcCouponRuleInfo> 卡券类营销活动规则表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/20 18:40
     */
    private List<TMMcCouponRuleInfo> getCouponMcRuleListInfo() throws Exception {

        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        return mcRuleInfoMapper.selectCouponRuleInfoList(globalInstId, globalMcNo);
    }

    /**
     * 减免类营销活动信息数据库实体类和接口实体类数据转换
     *
     * @param mcMoneyOffInfo 减免类营销活动信息表
     * @return cc.rengu.igas.momp.facade.bean.MoneyOffMcInfoBean 减免类活动基本信息对象
     * @author liujinan
     * @date 2020/4/1 10:27
     */
    private ToClientMcInfoBean moneyOffConvertMcInfo(TMMcMoneyOffInfo mcMoneyOffInfo) {
        ToClientMcInfoBean toClientMcInfoBean = new ToClientMcInfoBean();
        try {
            /* 营销活动编号 */
            toClientMcInfoBean.setMcNo(mcMoneyOffInfo.getMcNo());
            /* 营销活动名称 */
            toClientMcInfoBean.setMcName(mcMoneyOffInfo.getMcName());
            /* 营销活动类型 */
            toClientMcInfoBean.setMcType(mcMoneyOffInfo.getMcType());
            /* 营销活动状态 */
            toClientMcInfoBean.setMcStatus(mcMoneyOffInfo.getMcStatus());
            /* 活动起始日期 */
            toClientMcInfoBean.setMcStartDate(mcMoneyOffInfo.getMcStartDate());
            /* 活动截止日期 */
            toClientMcInfoBean.setMcEndDate(mcMoneyOffInfo.getMcEndDate());
            /* 活动结束日期 */
            toClientMcInfoBean.setMcActualEndDate(mcMoneyOffInfo.getMcActualEndDate());
            /* 活动时间标志 */
            toClientMcInfoBean.setMcTimeFlag(mcMoneyOffInfo.getMcTimeFlag());
            /* 出资方 */
            toClientMcInfoBean.setSponsor(mcMoneyOffInfo.getSponsor());
            /* 参与次数限制 */
            toClientMcInfoBean.setRestriction(mcMoneyOffInfo.getRestriction());
            /* 客户范围 */
            toClientMcInfoBean.setClientRange(mcMoneyOffInfo.getClientRange());
            /* 商户范围 */
            toClientMcInfoBean.setMerchantRange(mcMoneyOffInfo.getMerchantRange());
            /* 新增商户活动标志 */
            toClientMcInfoBean.setNewMchntFlag(mcMoneyOffInfo.getBudget());
            /* 限制金额下限 */
            toClientMcInfoBean.setAmtLimitFloor(mcMoneyOffInfo.getAmtLimitFloor());
            /* 限制金额上限 */
            toClientMcInfoBean.setAmtLimitCelling(mcMoneyOffInfo.getAmtLimitCelling());
            /* 预算充值方式 */
            toClientMcInfoBean.setBudgetRechargeMethod(mcMoneyOffInfo.getBudgetRechargeMethod());
            /* 预算 */
            toClientMcInfoBean.setBudget(mcMoneyOffInfo.getBudget());
            /* 银行出资预算 */
            toClientMcInfoBean.setBankBudget(mcMoneyOffInfo.getBankBudget());
            /* 预期参与商户数量 */
            toClientMcInfoBean.setExpectMchntQty(mcMoneyOffInfo.getExpectMchntQty());
            /* 审批状态   */
            toClientMcInfoBean.setAuditStatus(mcMoneyOffInfo.getAuditStatus());
            /* 创建人 */
            toClientMcInfoBean.setOprId(mcMoneyOffInfo.getOprId());
            /* 创建时间 */
            toClientMcInfoBean.setCreateTime(mcMoneyOffInfo.getCreateTime());
            /* 最后修改人 */
            toClientMcInfoBean.setLastOprId(mcMoneyOffInfo.getLastOprId());
            /* 修改时间 */
            toClientMcInfoBean.setUpdateTime(mcMoneyOffInfo.getUpdateTime());
            /* 审批拒绝原因 */
            toClientMcInfoBean.setAuditRefuseReason(mcMoneyOffInfo.getAuditRefuseReason());
            /* 发布拒绝原因 */
            toClientMcInfoBean.setPublishRefuseReason(mcMoneyOffInfo.getPublishRefuseReason());
            /* 备用字段1 */
            toClientMcInfoBean.setRemark1(mcMoneyOffInfo.getRemark1());
            /* 备用字段2 */
            toClientMcInfoBean.setRemark2(mcMoneyOffInfo.getRemark2());
            /* 备用字段3 */
            toClientMcInfoBean.setRemark3(mcMoneyOffInfo.getRemark3());
            /* 备用字段4 */
            toClientMcInfoBean.setRemark4(mcMoneyOffInfo.getRemark4());
            /* 备用字段5 */
            toClientMcInfoBean.setRemark5(mcMoneyOffInfo.getRemark5());
            /* 强制终止原因*/
            toClientMcInfoBean.setNfrcTmnlRsn(mcMoneyOffInfo.getNfrcTmnlRsn());

        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return toClientMcInfoBean;
    }

    /**
     * 卡券类营销活动信息数据库实体类和接口实体类数据转换
     *
     * @param tmMcCouponInfo 卡券类营销活动信息表
     * @return cc.rengu.igas.momp.facade.bean.CouponMcInfoBean 卡券类活动基本信息对象
     * @author liujinan
     * @date 2020/6/20
     */
    private ToClientMcInfoBean couponConvertMcInfo(TMMcCouponInfo tmMcCouponInfo) {
        ToClientMcInfoBean toClientMcInfoBean = new ToClientMcInfoBean();
        try {
            /* 法人机构号 */
            toClientMcInfoBean.setInstId(tmMcCouponInfo.getInstId());
            /* 营销活动编号 */
            toClientMcInfoBean.setMcNo(tmMcCouponInfo.getMcNo());
            /* 营销活动名称 */
            toClientMcInfoBean.setMcName(tmMcCouponInfo.getMcName());
            /* 营销活动类型 */
            toClientMcInfoBean.setMcType(tmMcCouponInfo.getMcType());
            /* 营销活动状态 */
            toClientMcInfoBean.setMcStatus(tmMcCouponInfo.getMcStatus());
            /* 活动起始日期 */
            toClientMcInfoBean.setMcStartDate(tmMcCouponInfo.getMcStartDate());
            /* 活动截止日期 */
            toClientMcInfoBean.setMcEndDate(tmMcCouponInfo.getMcEndDate());
            /* 活动结束日期 */
            toClientMcInfoBean.setMcActualEndDate(tmMcCouponInfo.getMcActualEndDate());
            /* 活动时间标志 */
            toClientMcInfoBean.setMcTimeFlag(tmMcCouponInfo.getMcTimeFlag());
            /* 出资方 */
            toClientMcInfoBean.setSponsor(tmMcCouponInfo.getSponsor());
            /* 参与次数限制 */
            toClientMcInfoBean.setRestriction(tmMcCouponInfo.getRestriction());
            /* 客户范围 */
            toClientMcInfoBean.setClientRange(tmMcCouponInfo.getClientRange());
            /* 商户范围 */
            toClientMcInfoBean.setMerchantRange(tmMcCouponInfo.getMerchantRange());
            /* 新增商户活动标志 */
            toClientMcInfoBean.setNewMchntFlag(tmMcCouponInfo.getBudget());
            /* 限制金额下限 */
            toClientMcInfoBean.setAmtLimitFloor(tmMcCouponInfo.getAmtLimitFloor());
            /* 限制金额上限 */
            toClientMcInfoBean.setAmtLimitCelling(tmMcCouponInfo.getAmtLimitCelling());
            /* 预算充值方式 */
            toClientMcInfoBean.setBudgetRechargeMethod(tmMcCouponInfo.getBudgetRechargeMethod());
            /* 预算 */
            toClientMcInfoBean.setBudget(tmMcCouponInfo.getBudget());
            /* 银行出资预算 */
            toClientMcInfoBean.setBankBudget(tmMcCouponInfo.getBankBudget());
            /* 预期参与商户数量 */
            toClientMcInfoBean.setExpectMchntQty(tmMcCouponInfo.getExpectMchntQty());
            /* 购买标志 */
            toClientMcInfoBean.setPurchaseFlag(tmMcCouponInfo.getPurchaseFlag());
            /* 卡券生效时间 */
            toClientMcInfoBean.setAvailableDate(tmMcCouponInfo.getAvailableDate());
            /* 卡券有效期标志 */
            toClientMcInfoBean.setCouponDateFlag(tmMcCouponInfo.getCouponDateFlag());
            /* 卡券有效起始日期 */
            toClientMcInfoBean.setCouponStartDate(tmMcCouponInfo.getCouponStartDate());
            /* 卡券有效结束日期 */
            toClientMcInfoBean.setCouponEndDate(tmMcCouponInfo.getCouponEndDate());
            /* 卡券相对周期 */
            toClientMcInfoBean.setCouponPeriod(tmMcCouponInfo.getCouponPeriod());
            /* 卡券库存 */
            toClientMcInfoBean.setCouponInventory(tmMcCouponInfo.getCouponInventory());
            /* 卡券未领取张数 */
            toClientMcInfoBean.setCouponRest(tmMcCouponInfo.getCouponRest());
            /* 卡券已领取张数 */
            toClientMcInfoBean.setCouponClaimed(tmMcCouponInfo.getCouponClaimed());
            /* 卡券已核销张数 */
            toClientMcInfoBean.setCouponRedeemed(tmMcCouponInfo.getCouponRedeemed());
            /* 审批状态   */
            toClientMcInfoBean.setAuditStatus(tmMcCouponInfo.getAuditStatus());
            /* 创建人 */
            toClientMcInfoBean.setOprId(tmMcCouponInfo.getOprId());
            /* 创建时间 */
            toClientMcInfoBean.setCreateTime(tmMcCouponInfo.getCreateTime());
            /* 最后修改人 */
            toClientMcInfoBean.setLastOprId(tmMcCouponInfo.getLastOprId());
            /* 修改时间 */
            toClientMcInfoBean.setUpdateTime(tmMcCouponInfo.getUpdateTime());
            /* 审批拒绝原因 */
            toClientMcInfoBean.setAuditRefuseReason(tmMcCouponInfo.getAuditRefuseReason());
            /* 发布拒绝原因 */
            toClientMcInfoBean.setPublishRefuseReason(tmMcCouponInfo.getPublishRefuseReason());
            /* 备用字段1 */
            toClientMcInfoBean.setRemark1(tmMcCouponInfo.getRemark1());
            /* 备用字段2 */
            toClientMcInfoBean.setRemark2(tmMcCouponInfo.getRemark2());
            /* 备用字段3 */
            toClientMcInfoBean.setRemark3(tmMcCouponInfo.getRemark3());
            /* 备用字段4 */
            toClientMcInfoBean.setRemark4(tmMcCouponInfo.getRemark4());
            /* 备用字段5 */
            toClientMcInfoBean.setRemark5(tmMcCouponInfo.getRemark5());
            /* 强制终止原因*/
            toClientMcInfoBean.setNfrcTmnlRsn(tmMcCouponInfo.getNfrcTmnlRsn());

        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        return toClientMcInfoBean;
    }

    /**
     * 减免类营销活动规则信息数据库实体类和接口实体类数据转换
     *
     * @param mcMoneyOffRuleInfoList 减免类营销活动规则表
     * @return cc.rengu.igas.momp.facade.bean.MoneyOffRuleInfoBean 减免类营销活动规则信息对象
     * @author liujinan
     * @date 2020/6/19 10:32
     */
    private List<MchntQueryMcRuleInfoBean> moneyOffConvertMcRuleInfo(TMMcMoneyOffInfo tmMcMoneyOffInfo, List<TMMcMoneyOffRuleInfo> mcMoneyOffRuleInfoList) {

        List<MchntQueryMcRuleInfoBean> mchntQueryMcRuleInfoBeanList = new ArrayList<>();
        try {
            String mcType = tmMcMoneyOffInfo.getMcType();
            for (TMMcMoneyOffRuleInfo tmMcMoneyOffRuleInfo : mcMoneyOffRuleInfoList) {
                MchntQueryMcRuleInfoBean mchntQueryMcRuleInfoBean = new MchntQueryMcRuleInfoBean();
                String ruleContent = "";
                switch (McTypeEnum.getByValue(mcType)) {
                    case REDUCTION_FIXED_AMOUNT:
                        ruleContent = "满" + tmMcMoneyOffRuleInfo.getCriteria() + "减" + tmMcMoneyOffRuleInfo.getDiscountCelling() + "元";
                        break;
                    case REDUCTION_RANDOM_AMOUNT:
                        ruleContent = "满" + tmMcMoneyOffRuleInfo.getCriteria() + "最低减" + tmMcMoneyOffRuleInfo.getDiscountFloor() + "元,最高减" + tmMcMoneyOffRuleInfo.getDiscountCelling() + "元";
                        break;
                    case REDUCTION_FIXED_RATE:
                        ruleContent = "满" + tmMcMoneyOffRuleInfo.getCriteria() + "打" + tmMcMoneyOffRuleInfo.getDiscountCelling() + "折, 最高优惠" + tmMcMoneyOffRuleInfo.getDiscountLimit() + "元";
                        break;
                    case REDUCTION_RANDOM_RATE:
                        ruleContent = "满" + tmMcMoneyOffRuleInfo.getCriteria() + "最低打" + tmMcMoneyOffRuleInfo.getDiscountFloor() + "折,最高打" + tmMcMoneyOffRuleInfo.getDiscountCelling() + "折, 最高优惠" + tmMcMoneyOffRuleInfo.getDiscountLimit() + "元";
                        break;
                    default:
                        return null;
                }
                //顺序号
                mchntQueryMcRuleInfoBean.setRuleIndex(tmMcMoneyOffRuleInfo.getRuleIndex());
                //活动门槛
                mchntQueryMcRuleInfoBean.setRuleContent(ruleContent);
                mchntQueryMcRuleInfoBeanList.add(mchntQueryMcRuleInfoBean);
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动规则信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return mchntQueryMcRuleInfoBeanList;
    }

    /**
     * 生成减免活动统计数据
     *
     * @author liujinan
     * @date 2020/6/19 10:32
     */
    private MoneyOffMcStatInfoBean getMoneyOffMcStatInfo(Object tmMcInfo, String mchntNo, String mcType) throws Exception {

        BigDecimal mcBudget = BigDecimal.ZERO, expectMchntQty = BigDecimal.ZERO, bankBudget = BigDecimal.ZERO;
        BigDecimal totalQtyAcc = BigDecimal.ZERO, totalAmtAcc = BigDecimal.ZERO, avgDiscountAmt = BigDecimal.ZERO;

        TMMcMoneyOffInfo tmMcMoneyOffInfo = new TMMcMoneyOffInfo();
        TMMcCouponInfo tmMcCouponInfo = new TMMcCouponInfo();

        tmMcMoneyOffInfo = (TMMcMoneyOffInfo) tmMcInfo;
        //活动预算
        mcBudget = new BigDecimal(tmMcMoneyOffInfo.getBudget());
        //预期参与商户数量
        expectMchntQty = new BigDecimal(tmMcMoneyOffInfo.getExpectMchntQty());
        //银行出资预算
        bankBudget = new BigDecimal(tmMcMoneyOffInfo.getBankBudget());
        //出资方
        String sponsor = tmMcMoneyOffInfo.getSponsor();

        int batchStatus = CommonConstant.FLAG_NOT_SET;
        String mcNo = ((TMMcMoneyOffInfo) tmMcInfo).getMcNo();
        String mcStartDate = ((TMMcMoneyOffInfo) tmMcInfo).getMcStartDate();
        String lastDate = DateUtil.getBaseDateOffsetDay(globalTxnDate, CommonConstant.MINUS_ONE);
        String lastSecondDate = DateUtil.getBaseDateOffsetDay(globalTxnDate, CommonConstant.MINUS_TWO);

        BigDecimal responsBudget = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
        String responsMchntBudget = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString();
        String responsBankBudget = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString();

        if (!CommonConstant.ZERO_COMMON_CONSTANT.equals(expectMchntQty.toString())) {
            //接口响应的预算
            responsBudget = mcBudget.divide(expectMchntQty, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            //接口响应商户补贴资金
            responsMchntBudget = (mcBudget.subtract(bankBudget).divide(expectMchntQty, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString());
            //接口响应银行补贴资金
            responsBankBudget = bankBudget.divide(expectMchntQty, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString();
        } else {
            //接口响应的预算
            responsBudget = mcBudget;
            //接口响应银行补贴资金
            responsBankBudget = mcBudget.toString();
        }

        //查询对客户营销活动统计表数据
        TMStat2C tmStat2C = selectToClientMcLevelStatistics(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);
        if (null == tmStat2C) {
            rglog.info("机构<{}> 营销活动<{}> 规则<{}> 对客户营销活动统计表无数据!", globalInstId, mcNo, CommonConstant.ZERO_COMMON_CONSTANT);

            /* 营销活动当前统计数据无值,可能是营销活动第一天,也可能是营销活动第二天但未跑第一天的批 */
            if (mcStartDate.equals(lastDate)) {
                rglog.info("机构<{}> 减免类营销活动<{}> 是昨天开始的营销活动，且今天未跑批完成!", globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);
                /* 营销活动是前一天开始的,未取到数据,说明当前的批还未跑,需要取前一天的统计数据 */
                batchStatus = CommonConstant.FLAG_SET;
                //取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2C.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            } else if (mcStartDate.equals(globalTxnDate)) {
                /* 营销活动是当天开始的,未取到数据,不需要取前一天的统计数据 */
                batchStatus = CommonConstant.FLAG_NOT_SET;
                /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2C.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            } else if (DateUtil.compareDate(mcStartDate, globalTxnDate) > 0) {
                /* 营销活动的开始时间在今天之后，没有统计数据也是正常的 */
                batchStatus = CommonConstant.FLAG_NOT_SET;
                /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2C.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            } else {
                /* 营销活动不是前一天或当天开始的,说明此时统计表数据理应有数据,未取到的话说明数据异常*/
                rglog.error("机构<{}> 减免类营销活动<{}> 对客户营销活动统计表数据异常!", globalInstId, mcNo);
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            }
        } else {
            if (!StringUtil.isNullorEmpty(tmStat2C.getUpdateTime())) {
                /* 营销活动当前统计数据有值,同时有最后更新日期,直接判断最后更新日期是否是当天即可 */
                String currentStatDate = tmStat2C.getUpdateTime().substring(0, 4) + tmStat2C.getUpdateTime().substring(5, 7) + tmStat2C.getUpdateTime().substring(8, 10);
                if (globalTxnDate.equals(currentStatDate)) {
                    /* 如果最后更新日期是当前,说明当天已跑完批,不需要再取前一天的数据 */
                    batchStatus = CommonConstant.FLAG_NOT_SET;
                } else if (lastDate.equals(currentStatDate)) {
                    /* 如果最后更新日期是昨天,说明当前数据未跑完,需要取前一天的数据 */
                    batchStatus = CommonConstant.FLAG_SET;
                } else {
                    //判断活动是否已经结束，如果结束了，正常，没结束，异常
                    String mcStatus = tmMcMoneyOffInfo.getMcStatus();
                    if (McStatusEnum.ENDED.getMcStatusCode().equals(mcStatus) ||
                            McStatusEnum.FORCE_ENDED.getMcStatusCode().equals(mcStatus) ||
                            McStatusEnum.ALL_ENDED.getMcStatusCode().equals(mcStatus)) {
                        batchStatus = CommonConstant.FLAG_NOT_SET;
                    } else {
                        /* 营销活动统计数据的更新时间不是今天也不是昨天，话说明数据异常*/
                        rglog.error("机构<{}> 减免类营销活动<{}> 对客户营销活动统计表数据异常!", globalInstId, mcNo);
                    }
                }
            } else {
                /* 营销活动当前统计数据有值,同时无最后更新日期,只能是营销活动第二天，第一天的批已经跑完了，第一次插入无更新时间,或者异常场景 也有可能是活动的第一天，批量提前跑了昨天的空数据*/
                if (mcStartDate.equals(lastDate) || mcStartDate.equals(globalTxnDate)) {
                    /* 当只能是营销活动第二天，第一天的批已经跑完了，第一次插入无更新时间,不需要取前一天的统计数据 */
                    batchStatus = CommonConstant.FLAG_NOT_SET;
                } else if (mcStartDate.equals(lastSecondDate)) {
                    /* 如果是营销活动第三天，出现这种情况是活动第二天的批已经跑完，但是当前批未跑完了，需要取前一天的统计数据 */
                    batchStatus = CommonConstant.FLAG_SET;
                } else {
                    /* 营销活动不是前一天开始的,说明此事统计表数据理应有数据,未取到的话说明数据异常,不可优惠 */
                    rglog.error("当前法人机构号<{}>商户手续费优惠营销活动<{}>对客户营销活动统计表数据异常", globalInstId, mcNo);
                }
            }
        }

        //查询对客户营销活动单日统计表数据
        TMStat2CDay tmStat2CDay = selectToClientMcDayStatistics(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT, globalTxnDate);
        if (null == tmStat2CDay) {
            rglog.error("机构<{}>的减免类营销活动<{}>的规则<{}>对客户营销活动单日统计表数据查询失败!", globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);
            //取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理
            tmStat2CDay = new TMStat2CDay();
            tmStat2CDay.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CDay.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
        }

        /* 需要取前一天的数据 */
        if (CommonConstant.FLAG_SET == batchStatus) {
            /* 查询对客户营销活动单日统计表数据 */
            TMStat2CDay tmStat2CDay1 = selectToClientMcDayStatistics(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT, lastDate);
            if (null == tmStat2CDay1) {
                rglog.info("机构<{}>的营销活动<{}>的规则<{}>手续费减免活动单日统计表数据查询失败!", globalInstId, mcNo, CommonConstant.ZERO_COMMON_CONSTANT);
                //取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理
                tmStat2CDay1 = new TMStat2CDay();
                tmStat2CDay1.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CDay1.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            }

            totalAmtAcc = new BigDecimal(tmStat2C.getTotalAmtAcc()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

            BigDecimal tmpAmtAcc = new BigDecimal(tmStat2CDay1.getTotalAmtAcc()).add(totalAmtAcc).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            BigDecimal tmpQtyAcc = new BigDecimal(tmStat2CDay1.getTotalQtyAcc()).add(new BigDecimal(tmStat2C.getTotalQtyAcc()));

            tmStat2C.setTotalAmtAcc(tmpAmtAcc.toString());
            tmStat2C.setTotalQtyAcc(tmpQtyAcc.toString());
        }

        /* 查询对客户营销活动商户统计表数据 */
        TMStat2CMchnt tmStat2CMchnt = selectToClientMcMchntStatistics(globalInstId, mcNo, mchntNo);
        if (null == tmStat2CMchnt) {
            rglog.info("机构<{}>的商户<{}>的减免类营销活动<{}>的对客户营销活动商户统计表数据查询为空!", globalInstId, mchntNo, mcNo);
            /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
            tmStat2CMchnt = new TMStat2CMchnt();
            tmStat2CMchnt.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setExposureQty(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setBankAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setBankQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setExposurePeopleQty(CommonConstant.ZERO_COMMON_CONSTANT);
        }

        /* 查询对客户营销活动商户单日统计表数据 */
        TMStat2CMchntDay tmStat2CMchntDay = selectToClientMcMchntDayStatistics(globalInstId, mcNo, mchntNo, globalTxnDate);
        if (null == tmStat2CMchntDay) {
            rglog.info("机构<{}>的商户<{}>的减免类营销活动<{}>的对客户营销活动商户统计表数据查询为空!", globalInstId, mchntNo, mcNo);
            /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
            tmStat2CMchntDay = new TMStat2CMchntDay();
            tmStat2CMchntDay.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setBankAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setBankQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setExposureQty(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setExposurePeopleQty(CommonConstant.ZERO_COMMON_CONSTANT);
        }

        /* 需要取前一天的数据 */
        if (CommonConstant.FLAG_SET == batchStatus) {
            rglog.info("当前活动需要获取前一天的商户单日统计信息...");
            /* 查询对客户营销活动商户单日统计表数据 */
            TMStat2CMchntDay tmStat2CMchntDay1 = selectToClientMcMchntDayStatistics(globalInstId, mcNo, mchntNo, lastDate);
            if (null == tmStat2CMchntDay1) {
                rglog.info("机构<{}>的商户<{}>的减免类营销活动<{}>的对客户营销活动商户单日统计表数据查询失败!", globalInstId, mchntNo, mcNo);
                /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
                tmStat2CMchntDay1 = new TMStat2CMchntDay();
                tmStat2CMchntDay1.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setBankAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setBankQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setExposureQty(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setExposurePeopleQty(CommonConstant.ZERO_COMMON_CONSTANT);
            }

            BigDecimal tmpQtyAcc = new BigDecimal(tmStat2CMchntDay1.getTotalQtyAcc()).add(new BigDecimal(tmStat2CMchnt.getTotalQtyAcc())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);
            BigDecimal tmpAmtAcc = new BigDecimal(tmStat2CMchntDay1.getTotalAmtAcc()).add(new BigDecimal(tmStat2CMchnt.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            BigDecimal tmpBabkQtyAcc = new BigDecimal(tmStat2CMchntDay1.getBankQtyAcc()).add(new BigDecimal(tmStat2CMchnt.getBankQtyAcc())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);
            BigDecimal tmpBankAmtAcc = new BigDecimal(tmStat2CMchntDay1.getBankAmtAcc()).add(new BigDecimal(tmStat2CMchnt.getBankAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            BigDecimal tmpExposureQty = new BigDecimal(tmStat2CMchntDay1.getExposureQty()).add(new BigDecimal(tmStat2CMchnt.getExposureQty())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);
            BigDecimal tmpExposurePeopleQty = new BigDecimal(tmStat2CMchntDay1.getExposurePeopleQty()).add(new BigDecimal(tmStat2CMchnt.getExposurePeopleQty())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);

            tmStat2CMchnt.setTotalQtyAcc(tmpQtyAcc.toString());
            tmStat2CMchnt.setTotalAmtAcc(tmpAmtAcc.toString());
            tmStat2CMchnt.setBankAmtAcc(tmpBankAmtAcc.toString());
            tmStat2CMchnt.setBankQtyAcc(tmpBabkQtyAcc.toString());
            tmStat2CMchnt.setExposureQty(tmpExposureQty.toString());
            tmStat2CMchnt.setExposurePeopleQty(tmpExposurePeopleQty.toString());
        }

        //总曝光次数
        BigDecimal exposureQty = new BigDecimal(tmStat2CMchnt.getExposureQty()).add(new BigDecimal(tmStat2CMchntDay.getExposureQty()));
        //总曝光人数
        BigDecimal exposurePeopleQty = new BigDecimal(tmStat2CMchnt.getExposurePeopleQty()).add(new BigDecimal(tmStat2CMchntDay.getExposurePeopleQty()));

        //剩余营销额度
        BigDecimal ruleIndex = new BigDecimal(CommonConstant.ZERO_AMOUNT).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
        //如果是银商联合或者银行创建银商联合免充值
        rglog.info("机构<{}> 减免类营销活动<{}> 活动出资方式为<{}>,剩余优惠额度开始计算...", globalInstId, mcNo, sponsor);
        if (CommonConstant.SPONSOR_MIXED.equals(sponsor) ||
                CommonConstant.SPONSOR_MCHNT.equals(sponsor)) {
            //总优惠笔数
            totalQtyAcc = new BigDecimal(tmStat2CMchnt.getTotalQtyAcc()).add(new BigDecimal(tmStat2CMchntDay.getTotalQtyAcc()));
            //总优惠金额
            totalAmtAcc = new BigDecimal(tmStat2CMchnt.getTotalAmtAcc()).add(new BigDecimal(tmStat2CMchntDay.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            //总笔均优惠金额
            if (CommonConstant.ZERO_COMMON_CONSTANT.equals(totalQtyAcc.toString())) {
                avgDiscountAmt = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            } else {
                avgDiscountAmt = totalAmtAcc.divide(totalQtyAcc, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            }

            //剩余营销额度
            ruleIndex = new BigDecimal(responsMchntBudget).subtract(totalAmtAcc).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

        } else if (CommonConstant.SPONSOR_BANK.equals(sponsor)) {
            //总优惠笔数
            totalQtyAcc = new BigDecimal(tmStat2CMchnt.getBankQtyAcc()).add(new BigDecimal(tmStat2CMchntDay.getBankQtyAcc()));
            //总优惠金额
            totalAmtAcc = new BigDecimal(tmStat2CMchnt.getBankAmtAcc()).add(new BigDecimal(tmStat2CMchntDay.getBankAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            //总笔均优惠金额
            if (CommonConstant.ZERO_COMMON_CONSTANT.equals(totalQtyAcc.toString())) {
                avgDiscountAmt = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            } else {
                avgDiscountAmt = totalAmtAcc.divide(totalQtyAcc, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            }

            //剩余营销额度
            ruleIndex = mcBudget.subtract(new BigDecimal(tmStat2C.getTotalAmtAcc())).subtract(new BigDecimal(tmStat2CDay.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

        } else if (CommonConstant.SPONSOR_MCHNT_NORECHARGE.equals(sponsor)) {
            //总优惠笔数
            totalQtyAcc = new BigDecimal(tmStat2CMchnt.getTotalQtyAcc()).add(new BigDecimal(tmStat2CMchntDay.getTotalQtyAcc()));
            //总优惠金额
            totalAmtAcc = new BigDecimal(tmStat2CMchnt.getTotalAmtAcc()).add(new BigDecimal(tmStat2CMchntDay.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            //总笔均优惠金额
            if (CommonConstant.ZERO_COMMON_CONSTANT.equals(totalQtyAcc.toString())) {
                avgDiscountAmt = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            } else {
                avgDiscountAmt = totalAmtAcc.divide(totalQtyAcc, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            }

            //剩余营销额度
            ruleIndex = mcBudget.subtract(new BigDecimal(tmStat2C.getTotalAmtAcc())).subtract(new BigDecimal(tmStat2CDay.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
        } else {
        }

        MoneyOffMcStatInfoBean moneyOffMcStatInfoBean = new MoneyOffMcStatInfoBean();
        moneyOffMcStatInfoBean.setRuleIndex(ruleIndex.toString());
        moneyOffMcStatInfoBean.setBudget(responsBudget.toString());
        moneyOffMcStatInfoBean.setMchntBudget(responsMchntBudget);
        moneyOffMcStatInfoBean.setBankBudget(responsBankBudget);
        moneyOffMcStatInfoBean.setExposureQty(exposureQty.toString());
        moneyOffMcStatInfoBean.setExposurePeopleQty(exposurePeopleQty.toString());
        moneyOffMcStatInfoBean.setDiscountQty(totalQtyAcc.toString());
        moneyOffMcStatInfoBean.setDiscountAmt(totalAmtAcc.toString());
        moneyOffMcStatInfoBean.setAvgDiscountAmt(avgDiscountAmt.toString());

        return moneyOffMcStatInfoBean;
    }

    /**
     * 生成卡券活动统计数据
     *
     * @author liujinan
     * @date 2020/6/20 10:32
     */
    private CouponMcStatInfoBean getCouponMcStatInfo(Object tmMcInfo, String mchntNo, String mcType) throws Exception {

        BigDecimal mcBudget = BigDecimal.ZERO, expectMchntQty = BigDecimal.ZERO, bankBudget = BigDecimal.ZERO;
        BigDecimal totalQtyAcc = BigDecimal.ZERO, totalAmtAcc = BigDecimal.ZERO, avgDiscountAmt = BigDecimal.ZERO;

        TMMcCouponInfo tmMcCouponInfo = new TMMcCouponInfo();

        tmMcCouponInfo = (TMMcCouponInfo) tmMcInfo;
        //活动预算
        mcBudget = new BigDecimal(tmMcCouponInfo.getBudget());
        //预期参与商户数量
        expectMchntQty = new BigDecimal(tmMcCouponInfo.getExpectMchntQty());
        //银行出资预算
        bankBudget = new BigDecimal(tmMcCouponInfo.getBankBudget());
        //出资方
        String sponsor = tmMcCouponInfo.getSponsor();

        int batchStatus = CommonConstant.FLAG_NOT_SET;
        String mcNo = tmMcCouponInfo.getMcNo();
        String mcStartDate = tmMcCouponInfo.getMcStartDate();
        String lastDate = DateUtil.getBaseDateOffsetDay(globalTxnDate, CommonConstant.MINUS_ONE);
        String lastSecondDate = DateUtil.getBaseDateOffsetDay(globalTxnDate, CommonConstant.MINUS_TWO);

        BigDecimal responsBudget = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
        String responsMchntBudget = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString();
        String responsBankBudget = BigDecimal.ZERO.setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString();

        if (!CommonConstant.ZERO_COMMON_CONSTANT.equals(expectMchntQty.toString())) {
            //接口响应的预算
            responsBudget = mcBudget.divide(expectMchntQty, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            //接口响应商户补贴资金
            responsMchntBudget = (mcBudget.subtract(bankBudget).divide(expectMchntQty, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString());
            //接口响应银行补贴资金
            responsBankBudget = bankBudget.divide(expectMchntQty, CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP).toString();
        } else {
            //接口响应的预算
            responsBudget = mcBudget;
            //接口响应银行补贴资金
            responsBankBudget = mcBudget.toString();
        }

        //查询对客户营销活动统计表数据
        TMStat2C tmStat2C = selectToClientMcLevelStatistics(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);
        if (null == tmStat2C) {
            rglog.info("机构<{}> 营销活动<{}> 规则<{}> 对客户营销活动统计表无数据!", globalInstId, mcNo, CommonConstant.ZERO_COMMON_CONSTANT);

            /* 营销活动当前统计数据无值,可能是营销活动第一天,也可能是营销活动第二天但未跑第一天的批 */
            if (mcStartDate.equals(lastDate)) {
                rglog.info("机构<{}> 减免类营销活动<{}> 是昨天开始的营销活动，且今天未跑批完成!", globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);
                /* 营销活动是前一天开始的,未取到数据,说明当前的批还未跑,需要取前一天的统计数据 */
                batchStatus = CommonConstant.FLAG_SET;
                //取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            } else if (mcStartDate.equals(globalTxnDate)) {
                /* 营销活动是当天开始的,未取到数据,不需要取前一天的统计数据 */
                batchStatus = CommonConstant.FLAG_NOT_SET;
                /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            } else if (DateUtil.compareDate(mcStartDate, globalTxnDate) > 0) {
                /* 营销活动的开始时间在今天之后，没有统计数据也是正常的 */
                batchStatus = CommonConstant.FLAG_NOT_SET;
                /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            } else {
                /* 营销活动不是前一天或当天开始的,说明此时统计表数据理应有数据,未取到的话说明数据异常*/
                rglog.error("机构<{}> 减免类营销活动<{}> 对客户营销活动统计表数据异常!", globalInstId, mcNo);
                tmStat2C = new TMStat2C();
                tmStat2C.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            }
        } else {
            if (!StringUtil.isNullorEmpty(tmStat2C.getUpdateTime())) {
                /* 营销活动当前统计数据有值,同时有最后更新日期,直接判断最后更新日期是否是当天即可 */
                String currentStatDate = tmStat2C.getUpdateTime().substring(0, 4) + tmStat2C.getUpdateTime().substring(5, 7) + tmStat2C.getUpdateTime().substring(8, 10);
                if (globalTxnDate.equals(currentStatDate)) {
                    /* 如果最后更新日期是当前,说明当天已跑完批,不需要再取前一天的数据 */
                    batchStatus = CommonConstant.FLAG_NOT_SET;
                } else if (lastDate.equals(currentStatDate)) {
                    /* 如果最后更新日期是昨天,说明当前数据未跑完,需要取前一天的数据 */
                    batchStatus = CommonConstant.FLAG_SET;
                } else {
                    //判断活动是否已经结束，如果结束了，正常，没结束，异常
                    String mcStatus = tmMcCouponInfo.getMcStatus();
                    if (McStatusEnum.ENDED.getMcStatusCode().equals(mcStatus) ||
                            McStatusEnum.FORCE_ENDED.getMcStatusCode().equals(mcStatus) ||
                            McStatusEnum.ALL_ENDED.getMcStatusCode().equals(mcStatus)) {
                        batchStatus = CommonConstant.FLAG_NOT_SET;
                    } else {
                        /* 营销活动统计数据的更新时间不是今天也不是昨天，话说明数据异常*/
                        rglog.error("机构<{}> 减免类营销活动<{}> 对客户营销活动统计表数据异常!", globalInstId, mcNo);
                    }
                }
            } else {
                /* 营销活动当前统计数据有值,同时无最后更新日期,只能是营销活动第二天，第一天的批已经跑完了，第一次插入无更新时间,或者异常场景 也有可能是活动的第一天，批量提前跑了昨天的空数据*/
                if (mcStartDate.equals(lastDate) || mcStartDate.equals(globalTxnDate)) {
                    /* 当只能是营销活动第二天，第一天的批已经跑完了，第一次插入无更新时间,不需要取前一天的统计数据 */
                    batchStatus = CommonConstant.FLAG_NOT_SET;
                } else if (mcStartDate.equals(lastSecondDate)) {
                    /* 如果是营销活动第三天，出现这种情况是活动第二天的批已经跑完，但是当前批未跑完了，需要取前一天的统计数据 */
                    batchStatus = CommonConstant.FLAG_SET;
                } else {
                    /* 营销活动不是前一天开始的,说明此事统计表数据理应有数据,未取到的话说明数据异常,不可优惠 */
                    rglog.error("当前法人机构号<{}>商户手续费优惠营销活动<{}>对客户营销活动统计表数据异常", globalInstId, mcNo);
                }
            }
        }

        //查询对客户营销活动单日统计表数据
        TMStat2CDay tmStat2CDay = selectToClientMcDayStatistics(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT, globalTxnDate);
        if (null == tmStat2CDay) {
            rglog.error("机构<{}>的减免类营销活动<{}>的规则<{}>对客户营销活动单日统计表数据查询失败!", globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT);
            //取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理
            tmStat2CDay = new TMStat2CDay();
            tmStat2CDay.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
        }

        /* 需要取前一天的数据 */
        if (CommonConstant.FLAG_SET == batchStatus) {
            /* 查询对客户营销活动单日统计表数据 */
            TMStat2CDay tmStat2CDay1 = selectToClientMcDayStatistics(globalInstId, globalMcNo, CommonConstant.ZERO_COMMON_CONSTANT, lastDate);
            if (null == tmStat2CDay1) {
                rglog.info("机构<{}>的营销活动<{}>的规则<{}>手续费减免活动单日统计表数据查询失败!", globalInstId, mcNo, CommonConstant.ZERO_COMMON_CONSTANT);
                //取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理
                tmStat2CDay1 = new TMStat2CDay();
                tmStat2CDay1.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            }

            totalAmtAcc = new BigDecimal(tmStat2C.getTotalAmtAcc()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

            BigDecimal tmpAmtAcc = new BigDecimal(tmStat2CDay1.getTotalAmtAcc()).add(totalAmtAcc).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

            tmStat2C.setTotalAmtAcc(tmpAmtAcc.toString());
        }

        /* 查询对客户营销活动商户统计表数据 */
        TMStat2CMchnt tmStat2CMchnt = selectToClientMcMchntStatistics(globalInstId, mcNo, mchntNo);
        if (null == tmStat2CMchnt) {
            rglog.info("机构<{}>的商户<{}>的减免类营销活动<{}>的对客户营销活动商户统计表数据查询为空!", globalInstId, mchntNo, mcNo);
            /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
            tmStat2CMchnt = new TMStat2CMchnt();
            tmStat2CMchnt.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setExposureQty(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchnt.setExposurePeopleQty(CommonConstant.ZERO_COMMON_CONSTANT);
        }

        /* 查询对客户营销活动商户单日统计表数据 */
        TMStat2CMchntDay tmStat2CMchntDay = selectToClientMcMchntDayStatistics(globalInstId, mcNo, mchntNo, globalTxnDate);
        if (null == tmStat2CMchntDay) {
            rglog.info("机构<{}>的商户<{}>的减免类营销活动<{}>的对客户营销活动商户统计表数据查询为空!", globalInstId, mchntNo, mcNo);
            /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
            tmStat2CMchntDay = new TMStat2CMchntDay();
            tmStat2CMchntDay.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setExposureQty(CommonConstant.ZERO_COMMON_CONSTANT);
            tmStat2CMchntDay.setExposurePeopleQty(CommonConstant.ZERO_COMMON_CONSTANT);
        }

        /* 需要取前一天的数据 */
        if (CommonConstant.FLAG_SET == batchStatus) {
            rglog.info("当前活动需要获取前一天的商户单日统计信息...");
            /* 查询对客户营销活动商户单日统计表数据 */
            TMStat2CMchntDay tmStat2CMchntDay1 = selectToClientMcMchntDayStatistics(globalInstId, mcNo, mchntNo, lastDate);
            if (null == tmStat2CMchntDay1) {
                rglog.info("机构<{}>的商户<{}>的减免类营销活动<{}>的对客户营销活动商户单日统计表数据查询失败!", globalInstId, mchntNo, mcNo);
                /* 取到0条数据,说明该营销活动还未产生统计值,按所有统计值都是0进行处理 */
                tmStat2CMchntDay1 = new TMStat2CMchntDay();
                tmStat2CMchntDay1.setTotalQtyAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setTotalAmtAcc(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setExposureQty(CommonConstant.ZERO_COMMON_CONSTANT);
                tmStat2CMchntDay1.setExposurePeopleQty(CommonConstant.ZERO_COMMON_CONSTANT);
            }

            BigDecimal tmpQtyAcc = new BigDecimal(tmStat2CMchntDay1.getTotalQtyAcc()).add(new BigDecimal(tmStat2CMchnt.getTotalQtyAcc())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);
            BigDecimal tmpAmtAcc = new BigDecimal(tmStat2CMchntDay1.getTotalAmtAcc()).add(new BigDecimal(tmStat2CMchnt.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
            BigDecimal tmpExposureQty = new BigDecimal(tmStat2CMchntDay1.getExposureQty()).add(new BigDecimal(tmStat2CMchnt.getExposureQty())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);
            BigDecimal tmpExposurePeopleQty = new BigDecimal(tmStat2CMchntDay1.getExposurePeopleQty()).add(new BigDecimal(tmStat2CMchnt.getExposurePeopleQty())).setScale(CommonConstant.DECIMAL_SCALE_ZERO, RoundingMode.HALF_UP);

            tmStat2CMchnt.setTotalQtyAcc(tmpQtyAcc.toString());
            tmStat2CMchnt.setTotalAmtAcc(tmpAmtAcc.toString());
            tmStat2CMchnt.setExposureQty(tmpExposureQty.toString());
            tmStat2CMchnt.setExposurePeopleQty(tmpExposurePeopleQty.toString());
        }

        //商户总优惠金额
        totalAmtAcc = new BigDecimal(tmStat2CMchnt.getTotalAmtAcc()).add(new BigDecimal(tmStat2CMchntDay.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

        //总曝光次数
        BigDecimal exposureQty = new BigDecimal(tmStat2CMchnt.getExposureQty()).add(new BigDecimal(tmStat2CMchntDay.getExposureQty()));
        //总曝光人数
        BigDecimal exposurePeopleQty = new BigDecimal(tmStat2CMchnt.getExposurePeopleQty()).add(new BigDecimal(tmStat2CMchntDay.getExposurePeopleQty()));

        //剩余营销额度
        BigDecimal ruleIndex = new BigDecimal(CommonConstant.ZERO_AMOUNT).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

        rglog.info("机构<{}> 卡券类营销活动<{}> 活动出资方式为<{}>,剩余优惠额度开始计算...", globalInstId, mcNo, sponsor);
        if (CommonConstant.SPONSOR_MIXED.equals(sponsor) ||
                CommonConstant.SPONSOR_MCHNT.equals(sponsor)) {
            //剩余营销额度
            ruleIndex = new BigDecimal(responsMchntBudget).subtract(totalAmtAcc).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

        } else if (CommonConstant.SPONSOR_BANK.equals(sponsor) ||
                CommonConstant.SPONSOR_MCHNT_NORECHARGE.equals(sponsor)) {
            //剩余营销额度
            ruleIndex = mcBudget.subtract(new BigDecimal(tmStat2C.getTotalAmtAcc())).subtract(new BigDecimal(tmStat2CDay.getTotalAmtAcc())).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
        } else {
        }

        //获取卡券总量couponQty
        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();
        TMMcCouponRuleInfo tmMcCouponRuleInfo = mcRuleInfoMapper.selectCouponAmountByMcNo(globalInstId, globalMcNo);
        if (null == tmMcCouponRuleInfo) {
            rglog.error("获取法人机构号<{}>卡券营销活动编号<{}>的卡券总量失败!", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespDesc());
        }
        //卡券总量
        String couponQty = tmMcCouponRuleInfo.getQuantity();

        //查询卡券规则列表数据
        List<TMMcCouponRuleInfo> tmMcCouponRuleInfoList = mcRuleInfoMapper.selectCouponRuleInfoList(globalInstId, globalMcNo);
        if (null == tmMcCouponRuleInfoList || tmMcCouponRuleInfoList.isEmpty()) {
            rglog.error("机构<{}>的卡券类营销活动<{}>的卡券类规则查询失败!", globalInstId, globalMcNo);
            throw new BizException(RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MC_RULE_INFO_ERROR.getRespDesc());
        }

        List<CouponMcRuleStatInfoBean> couponMcRuleStatInfoList = new ArrayList<>();
        //遍历规则列表,查询相应规则的卡券统计数据
        for (TMMcCouponRuleInfo tmMcCouponRule : tmMcCouponRuleInfoList) {
            int redeemedQty = 0, claimedQty = 0, availableQty = 0, expiredQty = 0;

            CouponMcRuleStatInfoBean couponMcRuleStatInfoBean = new CouponMcRuleStatInfoBean();
            couponMcRuleStatInfoBean.setRuleIndex(tmMcCouponRule.getRuleIndex());
            couponMcRuleStatInfoBean.setCouponAmt(tmMcCouponRule.getDenomination());
            couponMcRuleStatInfoBean.setCouponQty(tmMcCouponRule.getQuantity());

            //查询营销活动当前规则下的所有卡券信息
            CouponInfoMapper couponInfoMapper = new CouponInfoMapperImpl();
            List<TMCouponInfo> tmCouponInfoList = couponInfoMapper.selectCouponInfoListByRuleIndex(globalInstId, globalMcNo, tmMcCouponRule.getRuleIndex());
            if (null != tmCouponInfoList && !tmCouponInfoList.isEmpty()) {
                for (TMCouponInfo tmCouponInfo : tmCouponInfoList) {
                    if (CouponStatusEnum.REDEEMED.getCouponStatusCode().equals(tmCouponInfo.getCouponStatus())) {
                        //已核销卡券总量
                        redeemedQty++;
                    }
                    if ((CouponStatusEnum.NOT_REDEEMED.getCouponStatusCode().equals(tmCouponInfo.getCouponStatus()) ||
                            CouponStatusEnum.NOT_ENABLED.getCouponStatusCode().equals(tmCouponInfo.getCouponStatus())) &&
                            DateUtil.compareDate(globalTxnDate, tmCouponInfo.getCouponEndDate()) <= 0) {
                        //未核销的包含已领取未核销和已领取未生效的（卡券领取第二天生效）
                        if (CouponStatusEnum.NOT_REDEEMED.getCouponStatusCode().equals(tmCouponInfo.getCouponStatus())) {
                            //未核销卡券总量
                            claimedQty++;
                        } else {
                            //当卡券状态为9，未生效时，如果有领取人，则证明卡券已经被领取还未生效
                            String claimUserId = tmCouponInfo.getClaimUserId();
                            if (null != claimUserId) {
                                //未核销卡券总量
                                claimedQty++;
                            }
                        }
                    }
                    if (CouponStatusEnum.NOT_ENABLED.getCouponStatusCode().equals(tmCouponInfo.getCouponStatus()) &&
                            DateUtil.compareDate(globalTxnDate, tmCouponInfo.getCouponEndDate()) <= 0) {
                        //当卡券状态为9，未生效时，如果没有领取人，则证明卡券是可被领取的
                        String claimUserId = tmCouponInfo.getClaimUserId();
                        if (null == claimUserId) {
                            //可领取卡券总量
                            availableQty++;
                        }
                    }
                    if (CouponStatusEnum.RECYCLED.getCouponStatusCode().equals(tmCouponInfo.getCouponStatus()) &&
                            DateUtil.compareDate(globalTxnDate, tmCouponInfo.getCouponEndDate()) > 0) {
                        //已过期卡券总量
                        expiredQty++;
                    }
                }
            }
            couponMcRuleStatInfoBean.setRedeemedQty(String.valueOf(redeemedQty));
            couponMcRuleStatInfoBean.setClaimedQty(String.valueOf(claimedQty));
            couponMcRuleStatInfoBean.setAvailableQty(String.valueOf(availableQty));
            couponMcRuleStatInfoBean.setExpiredQty(String.valueOf(expiredQty));

            couponMcRuleStatInfoList.add(couponMcRuleStatInfoBean);
        }
        CouponMcStatInfoBean couponMcStatInfo = new CouponMcStatInfoBean();
        couponMcStatInfo.setRuleIndex(ruleIndex.toString());
        couponMcStatInfo.setBudget(responsBudget.toString());
        couponMcStatInfo.setMchntBudget(responsMchntBudget);
        couponMcStatInfo.setBankBudget(responsBankBudget);
        couponMcStatInfo.setExposureQty(exposureQty.toString());
        couponMcStatInfo.setExposurePeopleQty(exposurePeopleQty.toString());
        couponMcStatInfo.setCouponQty(couponQty);
        couponMcStatInfo.setCouponMcRuleStatInfo(couponMcRuleStatInfoList);

        return couponMcStatInfo;
    }

    /**
     * 查询对客户营销活动商户统计表数据
     *
     * @param instId  法人机构号
     * @param mcNo    营销活动编号
     * @param mchntNo 商户编号
     * @return cc.rengu.igas.momp.common.entity.TMStat2CMchnt 对客户营销活动商户统计表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/4/15 15:38
     */
    private TMStat2CMchnt selectToClientMcMchntStatistics(String instId, String mcNo, String mchntNo) throws Exception {

        TMStat2CMchnt tmStat2CMchnt = new TMStat2CMchnt();
        tmStat2CMchnt.setInstId(instId);
        tmStat2CMchnt.setMcNo(mcNo);
        tmStat2CMchnt.setMchntNo(mchntNo);

        TMStat2CMchntMapper tmStat2CMchntMapper = new TMStat2CMchntMapperImpl();
        return tmStat2CMchntMapper.selectToClientMcMchntStatistics(tmStat2CMchnt);
    }

    /**
     * 查询对客户营销活动商户单日统计表数据
     *
     * @param instId  法人机构号
     * @param mcNo    营销活动编号
     * @param mchntNo 商户编号
     * @return cc.rengu.igas.momp.common.entity.TMStat2CMchntDay 对客户营销活动商户单日统计表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/4/15 17:11
     */
    private TMStat2CMchntDay selectToClientMcMchntDayStatistics(String instId, String mcNo, String mchntNo, String txnDate) throws Exception {

        TMStat2CMchntDay tmStat2CMchntDay = new TMStat2CMchntDay();
        tmStat2CMchntDay.setInstId(instId);
        tmStat2CMchntDay.setMcNo(mcNo);
        tmStat2CMchntDay.setMchntNo(mchntNo);
        tmStat2CMchntDay.setTxnDate(txnDate);

        TMStat2CMchntDayMapper tmStat2CMchntDayMapper = new TMStat2CMchntDayMapperImpl();
        return tmStat2CMchntDayMapper.selectToClientMcMchntDayStatistics(tmStat2CMchntDay);
    }

    /**
     * 查询对客户营销活动统计表数据
     *
     * @param instId    法人机构号
     * @param mcNo      营销活动编号
     * @param ruleIndex 规则顺序号
     * @return cc.rengu.igas.momp.common.entity.TMStat2C 对客户营销活动统计表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/4/14 22:47
     */
    private TMStat2C selectToClientMcLevelStatistics(String instId, String mcNo, String ruleIndex) throws Exception {

        TMStat2C tmStat2C = new TMStat2C();
        tmStat2C.setInstId(instId);
        tmStat2C.setMcNo(mcNo);
        tmStat2C.setRuleIndex(ruleIndex);

        TMStat2CMapper tmStat2CMapper = new TMStat2CMapperImpl();
        return tmStat2CMapper.selectToClientMcLevelStatistics(tmStat2C);
    }

    /**
     * 查询对客户营销活动单日统计表数据
     *
     * @param instId    法人机构号
     * @param mcNo      营销活动编号
     * @param ruleIndex 规则顺序号
     * @return cc.rengu.igas.momp.common.entity.TMStat2CDay 对客户营销活动单日统计表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/4/14 22:52
     */
    private TMStat2CDay selectToClientMcDayStatistics(String instId, String mcNo, String ruleIndex, String txnDtae) throws Exception {

        TMStat2CDay tmStat2CDay = new TMStat2CDay();
        tmStat2CDay.setInstId(instId);
        tmStat2CDay.setMcNo(mcNo);
        tmStat2CDay.setRuleIndex(ruleIndex);
        tmStat2CDay.setTxnDate(txnDtae);
        TMStat2CDayMapper tmStat2CDayMapper = new TMStat2CDayMapperImpl();
        return tmStat2CDayMapper.selectToClientMcDayStatistics(tmStat2CDay);
    }

    /**
     * 卡券类营销活动规则信息数据库实体类和接口实体类数据转换
     *
     * @param tmMcCouponRuleInfoList 卡券类营销活动规则表
     * @author liujinan
     * @date 2020/6/20 10:32
     */
    private List<MchntQueryMcRuleInfoBean> couponConvertMcRuleInfo(List<TMMcCouponRuleInfo> tmMcCouponRuleInfoList) {

        List<MchntQueryMcRuleInfoBean> mchntQueryMcRuleInfoBeanList = new ArrayList<>();

        MchntQueryMcRuleInfoBean mchntQueryMcRuleInfoBean = new MchntQueryMcRuleInfoBean();

        try {
            for (TMMcCouponRuleInfo tmMcCouponRuleInfo : tmMcCouponRuleInfoList) {
                BigDecimal criteria = new BigDecimal(tmMcCouponRuleInfo.getCriteria()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
                BigDecimal denomination = new BigDecimal(tmMcCouponRuleInfo.getDenomination()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

                String ruleContent = "满" + criteria.toString() + "减" + denomination.toString();
                //顺序号
                mchntQueryMcRuleInfoBean.setRuleIndex(tmMcCouponRuleInfo.getRuleIndex());
                //活动门槛
                mchntQueryMcRuleInfoBean.setRuleContent(ruleContent);
                mchntQueryMcRuleInfoBeanList.add(mchntQueryMcRuleInfoBean);
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换营销活动规则信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return mchntQueryMcRuleInfoBeanList;
    }

    /**
     * 使用商户编号从内管商户基本信息表查询商户所属商圈编号
     *
     * @param globalInstId 法人机构号
     * @param mchntNo      商户编号
     * @return cc.rengu.igas.momp.common.entity.TBMchntBaseInfo 商户基本信息表T_B_MCHNT_BASE_INFO
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/19 13:06
     */
    private TBMchntBaseInfo selectMompMchntBaseInfoByPrimaryKey(String globalInstId, String mchntNo) throws Exception {
        MchntInfoMapper mchntInfoMapper = new MchntInfoMapperImpl();
        return mchntInfoMapper.selectMompMchntBaseInfoByPrimaryKey(globalInstId, mchntNo);
    }

    /**
     * 商户查询卡券营销活动基本信息表数据,无商圈
     *
     * @param cpMcListInfoInObj 营销活动列表查询使用实体类入参
     * @return cc.rengu.igas.momp.common.entity.TMMcCouponInfo 卡券类营销活动信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/20
     */
    private TMMcCouponInfo selectCouponMcDetailInfoByMchnt(CpMcListInfoInObj cpMcListInfoInObj) throws Exception {
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.selectCouponMcDetailInfoByMchnt(cpMcListInfoInObj);
    }

    /**
     * 商户查询卡券营销活动基本信息表数据,有商圈
     *
     * @param cpMcListInfoInObj 营销活动列表查询使用实体类入参
     * @return cc.rengu.igas.momp.common.entity.TMMcCouponInfo 卡券类营销活动信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/6/20
     */
    private TMMcCouponInfo selectCouponMcDetailInfoByMchntWithArea(CpMcListInfoInObj cpMcListInfoInObj) throws Exception {
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        return mcDetailInfoMapper.selectCouponMcDetailInfoByMchntWithArea(cpMcListInfoInObj);
    }

    /**
     * 获取营销活动用户信息列表
     *
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMMcUserInfo> 营销活动用户信息表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2021/1/25 18:38
     */
    private List<TMMcUserInfo> getAllMcUserListInfo() throws Exception {

        McUserInfoMapper mcUserInfoMapper = new McUserInfoMapperImpl();
        return mcUserInfoMapper.selectMcUserInfoList(globalInstId, globalMcNo);
    }

    /**
     * 营销活动用户规则信息数据库实体类和接口实体类数据转换
     *
     * @param mcUserInfo 营销活动用户信息表
     * @return cc.rengu.igas.momp.facade.bean.McUserInfoBean 营销活动用户信息对象
     * @author liujinan
     * @date 2020/4/1 10:33
     */
    private McUserInfoBean convertMcUserInfo(TMMcUserInfo mcUserInfo) {
        McUserInfoBean mcUserInfoBean = new McUserInfoBean();
        /* 账户类型 */
        mcUserInfoBean.setAcctType(mcUserInfo.getAcctType());
        /* 账户 */
        mcUserInfoBean.setAcctNo(mcUserInfo.getAcctNo());
        /* 会员ID */
        mcUserInfoBean.setMemberId(mcUserInfo.getMemberId());
        /* 每日限制优惠次数 */
        mcUserInfoBean.setDayRestriction(mcUserInfo.getDayRestriction());
        /* 每周限制优惠次数 */
        mcUserInfoBean.setWeekRestriction(mcUserInfo.getWeekRestriction());
        /* 每月限制优惠次数 */
        mcUserInfoBean.setMonthRestriction(mcUserInfo.getMonthRestriction());
        /* 每季度限制优惠次数 */
        mcUserInfoBean.setQuerterRestriction(mcUserInfo.getQuerterRestriction());
        /* 每年限制优惠次数 */
        mcUserInfoBean.setYearRestriction(mcUserInfo.getYearRestriction());
        /* 活动期间优惠次数限制 */
        mcUserInfoBean.setRestriction(mcUserInfo.getRestriction());
        /** 账户标志 */
        mcUserInfoBean.setAcctFlag(mcUserInfo.getAcctFlag());

        return mcUserInfoBean;
    }
}

